import { NestFactory } from '@nestjs/core';
import * as cookieParser from 'cookie-parser';
import { AppModule } from './app.module';
import { ResponseInterceptor } from './common/interceptor/Response';
import { GlobalExceptionFilter } from './common/interceptor/ExceptionFilter';
import { ConfigService } from '@nestjs/config';

const initNest = async () => {
  // 异常时不停止服务，开启跨域
  const app = await NestFactory.create(AppModule, { abortOnError: false });

  // 获取配置
  const configService = app.get(ConfigService);

  // 本地开启跨域
  const isDev = configService.get('NODE_ENV') === 'development';
  if (isDev) app.enableCors();

  // 应用cookie中间件
  app.use(cookieParser());
  // 响应拦截器
  app.useGlobalInterceptors(new ResponseInterceptor());

  // 异常拦截器
  app.useGlobalFilters(new GlobalExceptionFilter());

  // 设置api前缀，nestjs自动补全 / ，/user -> /api/user
  app.setGlobalPrefix(configService.get('API_PREFIX'));

  // 监听端口
  await app.listen(configService.get('PORT'));
};

async function bootstrap() {
  try {
    await initNest();
  } catch (e) {
    if (e instanceof AggregateError) {
      (e?.errors || []).forEach((err) => {
        console.error('Nest Error:', err.message);
      });
    }
  }
}

bootstrap();
